package com.truthbean.log;

import com.truthbean.log.exception.NoLoggerProviderException;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @author TruthBean
 * @since 0.0.1
 */
public final class LoggerFactory {

    /**
     * Marker to be used by logging implementations that support markers.
     */
    public static final String MARKER = "TruthBean";

    private LoggerFactory() {
    }

    /**
     * get logger by class
     *
     * @param clazz class
     * @return class
     */
    public static Logger getLogger(Class<?> clazz) {
        return getLogger(clazz.getName());
    }

    /**
     * get logger by class name
     *
     * @param loggerName class name
     * @return logger
     */
    public static Logger getLogger(String loggerName) {
        try {
            ServiceLoader<Logger> serviceLoader = ServiceLoader.load(Logger.class);
            Iterator<Logger> iterator = serviceLoader.iterator();
            if (iterator.hasNext()) {
                Logger logger = iterator.next();
                logger.setClassName(loggerName);
                return logger;
            } else {
                throw new NoLoggerProviderException();
            }
        } catch (Throwable error) {
            throw new RuntimeException("Error creating logger for logger '" +
                    loggerName + "'.  Cause: " + error, error);
        }
    }
}